﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewAI.FSM
{
    public class FSMManager
    {
        private FSMManager() { }

        private static FSMManager instance;
        public static FSMManager GetInstance()
        {
            lock ("FSMManager")
            {
                if (instance == null)
                    instance = new FSMManager();
            }
            return instance;
        }

        public SocketConnectFSM.AIClientSocket ClientFSM { private set; get; }
        public JsonAnalyzerFSM.JsonAnalyzer JsonFSM { private set; get; }
        public List<TankFSM.TankAI> TankAIFSMs { private set; get; }

        public void InitFSM(string host, int port, TeamInfo teamInfo, int aiActionTimeOut)
        {
            instance.ClientFSM = new SocketConnectFSM.AIClientSocket(host, port, teamInfo);
            instance.JsonFSM = new JsonAnalyzerFSM.JsonAnalyzer((int)(aiActionTimeOut * 0.8));
            instance.TankAIFSMs = new List<TankFSM.TankAI>();
            for (int i = 0; i < 4; i++)//TODO:注意坦克数量
                instance.TankAIFSMs.Add(new TankFSM.TankAI(i + 1));

            //图1和图2
            instance.ClientFSM.ReceiveGameServerDataMessage.OnEvent += instance.JsonFSM.OnReceiveGameServerDataMessage;
            instance.JsonFSM.ActionMessage.OnEvent += instance.ClientFSM.OnReceiveActionJson;

            //图2和图3
            foreach (var item in TankAIFSMs)
            {
                instance.JsonFSM.LegStartMessage.OnEvent += item.OnReceiveLegStartMessage;
                instance.JsonFSM.OneRoundMessage.OnEvent += item.OnReceiveRoundMessage;
                instance.JsonFSM.LegEndMessage.OnEvent += item.OnReceiveLegEndMessage;

                item.ActionObjToJsonAnalyzer.OnEvent += instance.JsonFSM.OnReceiveTankAIActionMessage;

                // PubliceMessage.AnswerAssistanceToOtherTanks.OnEvent += item.OnReceiveAssistanceMessage;
                PubliceMessage.RequireAssistanceToOtherTanks.OnEvent += item.OnReceiveAssistanceMessage;

                item.FinishTankActionMessage.OnEvent += instance.JsonFSM.OnReceiveTankAIActionMessage;
            }
        }

        public void Close(AsyncCallback onCloseFinish)
        {
            PubliceMessage.CloseAllMessage.Call(null, new FSMEventEventArg("用户断开了连接。"), onCloseFinish);
            ClientFSM = null;
            JsonFSM = null;
            TankAIFSMs = null;
        }
    }
}
